package top.xmj.controller;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xmj.domain.UserBO;
import top.xmj.pojo.User;
import top.xmj.pojo.Register;
import top.xmj.service.IUserService;
import top.xmj.util.JWTUtils;
import top.xmj.util.RedisUtil;
import top.xmj.vo.ResultVO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


/**
 *
 * @author 冰咖啡
 * @Date:2/12/2022 下午 9:36
 * @Description: 用户操作
 *
 */
@RestController
@RequestMapping("/user")
@ApiModel("用户操作")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResultVO login(@RequestBody User user, HttpServletResponse response, HttpSession session)  {
        Map<String, Object> map = userService.login(user);
        //将token存入Http的header中
        response.setHeader(JWTUtils.USER_LOGIN_TOKEN, (String) map.get("token"));
        if(map.get("user")==null) {
            return new ResultVO(404,"登录失败，用户名或密码错误！",null);
        }
        session.setAttribute("token",map.get("token"));
        return new ResultVO(200,"登陆成功",map);
    }

    @PostMapping("/logout")
    @ApiOperation("用户退出")
    public ResultVO logout(@RequestParam(name = "token")String token){
        userService.logout(token);
        return new ResultVO(200,"退出登录",null);
    }

    @GetMapping("/user")
    @ApiOperation("获取用户列表")
    public ResultVO getUsers(){
        List<User> users = userService.getUsers();
        System.out.println(users);
        return new ResultVO(200,"获取成功",users);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ResultVO register(@RequestBody Register register, HttpServletResponse response, HttpSession session)  {
        String key = "code-" + register.getEmail();
        String CODE = (String) redisUtil.get(key);
        User uuu = userService.queryByName(register.getUsername());
        if(uuu!=null){
            return new ResultVO(405,"该用户名已存在！",null);
        }
        User uu = userService.queryByMail(register.getEmail());
        //验证码是否正确
        if(CODE==null||!register.getCode().equals(CODE)){
            return new ResultVO(405,"验证码错误",null);
        }
        //该邮箱是否已被注册
        if(uu!=null) {
            return new ResultVO(405,"注册失败,该邮箱已被注册！",null);
        }
        boolean res = userService.addUser(new User(register.getUsername(), register.getPassword(),register.getEmail()));
        if(!res) {
            return new ResultVO(505,"注册失败！",null);
        }
        return new ResultVO(200,"注册成功！",null);
    }

    @PutMapping("/user")
    @ApiOperation("更改个人信息")
    public ResultVO upadteInfo(@RequestBody UserBO u){
        User user = new User();
        user.setId(u.getId());
        user.setUsername(u.getUsername());
        user.setAvatar(u.getAvatar());
        user.setNickName(u.getNickName());
        User oldUser = userService.queryById(u.getId());
        if(oldUser == null){
            return new ResultVO(404,"该用户不存在",null);
        }
        if(u.getOldPassword() != null && u.getOldPassword() != ""){
            user.setPassword(u.getNewPassword());
            if(!oldUser.getPassword().equals(u.getOldPassword())){
                return new ResultVO(404,"原密码错误",null);
            }
        }
        if(!u.getUsername().equals(oldUser.getUsername())){
            User uu = userService.queryByName(u.getUsername());
            if(uu!=null) {
                return new ResultVO(405,"该用户名已存在！",null);
            }
        }
        int res = userService.updateInfo(user);
        if(res!=1) {
            return new ResultVO(505,"修改失败",null);
        }
        return new ResultVO(200,"修改成功",user);
    }


    @PostMapping("/getInfo")
    @ApiOperation("获取个人信息")
    public ResultVO getInfo(@RequestParam(name = "token") String token){
        User user = userService.getInfoByToken(token);
        if(user==null){
            return new ResultVO(405,"token失效",null);
        }
        return new ResultVO(200,"获取成功",user);
    }
}
